package com.pmcc.core.service;

import java.util.*;

import com.pmcc.core.dto.EmployeeMyself;
import com.pmcc.core.dto.Menu;
import com.pmcc.core.dto.TreeMenuNode;
import com.pmcc.core.entity.enums.ModuleType;
import com.pmcc.core.entity.security.Authority;
import com.pmcc.core.entity.security.Role;
import com.pmcc.core.repository.AuthorityRepository;
import com.pmcc.core.repository.RoleRepository;
import com.pmcc.core.vo.MenuVo;
import com.pmcc.core.web.EmployeeController;
import com.pmcc.utils.BeanUtils;
import com.pmcc.utils.AntdPage;
import com.pmcc.utils.ResultBean;
import com.pmcc.utils.VOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by syk on 17/7/6.
 */
@Service
public class AuthorityService {
  /*  @Autowired
    private AuthorityRepository authorityRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    EmployeeController employeeController;
*/

    /**
     * 查询列表
     *
     * @return
     */
   /* public ResultBean queryList(AntdPage antdPage, Menu menu) {
        ResultBean resultBean=new ResultBean(ResultBean.SUCCESS);
        Map<String,List> map=new HashMap<>();
        //List<Authority> authorityList=authorityRepository.findByparentId("-1");
        List<Authority> authorityList=new ArrayList<>();
        if(menu.getBpid()!=null &&  !"".equals(menu.getBpid())){
            //authorityPage=authorityRepository.findByparentId(antdPage.getPageRequest(),menu.getBpid());
            authorityList=authorityRepository.findByparentId(menu.getBpid());
        }else{
            //authorityPage=authorityRepository.findByparentId(antdPage.getPageRequest(),"-1");
            authorityList=authorityRepository.findByparentId("-1");
        }
        List<MenuVo> voList=new ArrayList<>();
        for (Authority a:authorityList) {
            MenuVo menuVo= VOUtil.getMenuVo(this.getByAuthority(a));
            //子节点
            List<MenuVo> children=this.getChildren(menuVo);//获取第二节点
            for (MenuVo vo:children) {
                List<MenuVo> child=this.getChildren(vo);//第三节点
                if(child.size()>0){
                    vo.setChildren(child);
                }
            }
            if(children.size()>0){
                menuVo.setChildren(children);
            }
            voList.add(menuVo);
        }
        resultBean.setRows(voList);
        return resultBean;
    }


    public List<MenuVo> getChildren(MenuVo menuVo){
        List<MenuVo> children=new ArrayList<>();
        List<Authority> childrenAuthority=authorityRepository.findByparentId(menuVo.getId());
        if(childrenAuthority.size()>0){
            for (Authority c:childrenAuthority) {
                MenuVo vo= VOUtil.getMenuVo(this.getByAuthority(c));
                children.add(vo);
            }
        }
        return children;
    }

    *//**
     * Authority --> Menu
     *
     * @param authority
     * @return
     *//*
    public Menu getByAuthority(Authority authority){
        Menu menu=null;
        if(authority!=null){
            String parentName="";
            Authority father=authorityRepository.getOne(authority.getParentId());
            if(!authority.getParentId().equals("-1")){
                parentName=father.getName();
            }
            menu=new Menu(authority.getId(), authority.getParentId(), authority.getParentId(), authority.getIcon(), authority.getName(), authority.getRouter(),authority.getCode(),parentName,authority.getPath(),authority.getIndexPath(),authority.getPath()
            );
        }
        return menu;
    }


    public  List<Menu> getAllMenus() {
        List<Authority> authorities = authorityRepository.findAll();
        List<Menu> menus = new ArrayList<>();
        for (Authority authority : authorities) {
            String parentName="";
            Authority father=authorityRepository.getOne(authority.getParentId());
            if(!authority.getParentId().equals("-1")){
                parentName=father.getName();
            }
            menus.add(new Menu(authority.getId(), authority.getParentId(), authority.getParentId(), authority.getIcon(), authority.getName(), authority.getRouter(),authority.getCode(),parentName,authority.getPath(),authority.getIndexPath(),authority.getPath()
            ));
        }
        return menus;
    }


    public  List<MenuVo> queryMenuByToken(String token) {
        Map<String,EmployeeMyself> map=employeeController.getAuthenticatedUser(token,null);
        List<Authority> authorities=new ArrayList<>();
        if(map.containsKey("employee")){
            Set<String> visit=map.get("employee").getPermissions().getVisit();//获取用户相对应的菜单权限
            for (String id:visit) {
                Authority authority=authorityRepository.getOne(id);
                if(authority!=null){
                    authorities.add(authority);
                }
            }
        }

        List<Menu> menus = new ArrayList<>();
        for (Authority authority : authorities) {
            String parentName="";
            Authority father=authorityRepository.getOne(authority.getParentId());
            if(!authority.getParentId().equals("-1")){
                parentName=father.getName();
            }
            menus.add(new Menu(authority.getId(), authority.getParentId(), authority.getParentId(), authority.getIcon(), authority.getName(), authority.getRouter(),authority.getCode(),parentName,authority.getPath(),authority.getIndexPath(),authority.getPath()
            ));
        }
        List<MenuVo> voList=new ArrayList<>();
        for (Menu m:menus) {
            MenuVo vo=VOUtil.getMenuVo(m);
            voList.add(vo);
        }
        return voList;
    }


    public List<TreeMenuNode>  getMenuTreeNodes(){
        List<Authority> baseMenus= authorityRepository.findByparentId("-1");
        return generateTreeNodes(baseMenus);
    }

    private List<TreeMenuNode> generateTreeNodes(List<Authority> authorities){
        List<TreeMenuNode> treeMenuNodes=new ArrayList<>();

        for(Authority authority : authorities){
            TreeMenuNode treeMenuNode ;
            if(isLeaf(authority)){
                treeMenuNode= mapToTreeNode(authority,true);
            }else{
                treeMenuNode= mapToTreeNode(authority,false);
                treeMenuNode.setChildren(generateTreeNodes( authorityRepository.findByparentId(authority.getId())));
            }
            treeMenuNodes.add(treeMenuNode);
        }


        return treeMenuNodes;
    }

    private boolean isLeaf(Authority authority){

        return authority.getLeaf();
    }

    private TreeMenuNode mapToTreeNode(Authority authority,Boolean isLeaf){
        TreeMenuNode menuNode=new TreeMenuNode();
        menuNode.setName(authority.getName());
        menuNode.setKey(authority.getId());
        menuNode.setLeaf(isLeaf);
        return menuNode;

    }

    *//**
     * 根据菜单id获取按钮
     *
     * @param roleIds 角色id
     * @param id      菜单id
     * @return
     *//*
    @Transactional(readOnly = true)
    public String queryModuleButtons(List<String> roleIds, String id) {
        List<Role> roles = new ArrayList<>();
        List<Authority> listAll = new ArrayList<>();
        List<Authority> list = new ArrayList<>();
        String res = "";
        if (roleIds != null && roleIds.size() > 0) {
            for (String roleId : roleIds) {
                roles = roleRepository.findById(roleId);
                listAll.removeAll(null);
                listAll.addAll(null);
            }
            if (listAll != null && listAll.size() > 0) {
                for (int i = 0; i < listAll.size(); i++) {
                    if (id.equals(listAll.get(i).getParentId()) && ModuleType.BUTTON.equals(listAll.get(i).getModuleType())) {
                        list.add(listAll.get(i));
                    }
                }
            }
            if(list!=null && list.size()>0){
                Collections.sort(list, new Comparator<Authority>() {    //排序
                    @Override
                    public int compare(Authority o1, Authority o2) {
                        int i = o1.getSortNo() - o2.getSortNo();
                        return i;
                    }
                });
            }


            // 按钮所属菜单
            List<Authority> module = authorityRepository.findById(id);
            if (module != null) {
//                if ("0".equals(module.get(0).getSearchBar())) {
                // 包含搜索框
//                    res = this.getToolBarNoSearch(list);
//                } else {
                // 不包含搜索框
                if (list != null && list.size() > 0) {
                    for (Authority baseModule : list) {
                        res += "<a href=\"#\" class=\"easyui-linkbutton " + baseModule.getIcon() + "\" onclick=\"" + baseModule.getClickEvent() + "();\">"
                                + "<i class=\"iconfont\"><span style=\"color: #0163ac\">" + baseModule.getIcon()
                                + "</i>&nbsp;" + baseModule.getName() + "</span></a>&nbsp;&nbsp;";
                    }
                }
//                }
            }
        }
        return res;
    }


    *//**
     * 修改
     *
     * @param map
     * @return
     *//*
    public ResultBean update(Map<String,String> map){
        ResultBean resultBean=new ResultBean(ResultBean.SUCCESS);
        Authority old=authorityRepository.findOne(map.get("id").toString());
        if(old!=null){
            BeanUtils.setBeanData(old,map);
            *//*old.setParentId(authority.getParentId());
            old.setName(authority.getName());
            old.setCode(authority.getCode());
            old.setRouter(authority.getRouter());
            *//*
            authorityRepository.save(old);
        }
        return resultBean;
    }

*/
}
